<template>
    <el-card>
      
       <!-- 新增|刷新 -->
       <ListHeader @create="handleCreate" @refresh="getData"/>
   
       <el-table :data="tableData"  v-loading="loading">
         <el-table-column prop="id" label="序號" />
         <el-table-column prop="role_name" label="角色名称" />
        
      
         <el-table-column prop="created_at" label="創建時間"  />
    
         <el-table-column label="操作"  align="center">
           <template #default="{row}">
             <!-- <small v-if="row.id == 1" class="text-sm text-gray-500">暂无操作</small> -->
             <!-- <div v-else> -->

              <el-button type="success" size="small" @click="openSetRule(row)" >配置权限</el-button>
               <el-button type="primary" size="small"  @click="handleEdit(row)">修改</el-button>

             <el-popconfirm title="是否要删除该管理员？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDelete(row.id)">
                   <template #reference>
                       <el-button type="danger" size="small">删除</el-button>
                   </template>
               </el-popconfirm>
             <!-- </div> -->
           </template>
         </el-table-column>
         
       </el-table>
   
       <div class="flex items-center justify-center mt-5">
           <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit" @current-change="getData"/>
       </div>
   
       <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
         <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
           <el-form-item label="角色名" prop="role_name">
             <el-input v-model="form.role_name" placeholder="角色名"></el-input>
           </el-form-item>
         
         </el-form>
       </FormDrawer>


           <!-- 权限配置 -->
    <FormDrawer ref="setRuleFormDrawerRef" title="權限配置" @submit="handleSetRuleSubmit">
      <el-tree-v2 ref="elTreeRef" node-key="id" :check-strictly="checkStrictly" :default-expanded-keys="defaultExpandedKeys" :data="ruleList" :props="{ label:'name',children:'child' }"  show-checkbox :height="treeHeight"
       @check="handleTreeCheck">
          <template #default="{ node,data }">
            <div class="flex items-center">
              <el-tag :type="data.is_menu ? '' : 'info'" size="small">
                {{ data.is_menu ? "菜單" : "權限" }}
              </el-tag>
              <span class="ml-2 text-sm"> {{ data.name }} </span>
            </div>
          </template>
       </el-tree-v2>
    </FormDrawer>

    </el-card>
   </template>
   
    <script setup>
   import { ref } from "vue"
   import ListHeader from "@/components/ListHeader.vue";
   import FormDrawer from "@/components/FormDrawer.vue";
   import { useInitTable,useInitForm } from '@/composables/useCommon.js'
   import {getrule} from "@/api/access.js"
   import {getrole,del,update,create} from "@/api/role.js"
   import {msg} from "@/composables/util"
   const {
     tableData,
     loading,
     currentPage,
     total,
     limit,
     getData,
     handleDelete
   } = useInitTable({
     getList:getrole,
     delete:del,
    
   })
   
   const {
     formDrawerRef,
     formRef,
     form,
     rules,
     drawerTitle,
     handleSubmit,
     handleCreate,
     handleEdit
   } = useInitForm({
     form:{
        role_name: "",
     },
     getData,
     update:update,
     create:create
   })

const setRuleFormDrawerRef = ref(null)
const ruleList = ref([])
const treeHeight = ref(0)
const roleId = ref(0)
const defaultExpandedKeys = ref([])
const elTreeRef = ref(null)
// 当前角色拥有的权限ID
const ruleIds = ref([])
const checkStrictly = ref(false)

const openSetRule=(row)=>{
  roleId.value=row.id
  treeHeight.value=window.innerHeight - 180
  checkStrictly.value = true
  getrule(1).then(res=>{
   
    ruleList.value=res.list
    defaultExpandedKeys.value = res.list.map(o=>o.id)
    setRuleFormDrawerRef.value.open()
    // 当前角色拥有的权限ID
    let ids=row.rule_id.split(',')
    ruleIds.value= ids.map(Number)
    setTimeout(() => {
      elTreeRef.value.setCheckedKeys(ruleIds.value)
      checkStrictly.value = false
    }, 150);
  })
}
   
const handleSetRuleSubmit=()=>{
  setRuleFormDrawerRef.value.showLoading()
  update(roleId.value,{rule_id:ruleIds.value.join(',')}).then(res=>{
    msg("配置成功")
    getData()
    setRuleFormDrawerRef.value.close()
  }).finally(()=>{
    setRuleFormDrawerRef.value.closeLoading()
  })
}

const handleTreeCheck=(...e)=>{
  const { checkedKeys,halfCheckedKeys } = e[1]
  ruleIds.value = [...checkedKeys,...halfCheckedKeys]
}   
   </script>
   
   